var Search = {
	WHAT : 'what',
	QUERY : 'query',
	value : {
		ABILITY : 'ability',
		FRIEND : 'friend'
	}
};

var AddAbility = {
	QUERY : 'addability'
};

var Action = {
	AUTOCOMPLETENAME : 'autocompleteName',
	AUTOCOMPLETEABILITY : 'autocompleteAbility',
	ADDABILITY : 'addability',
	REMOVEABILITY : 'removeability'
};

$(function() {
	// For all pages

	function mainSearchUpdater(item) {
		var action = $('input[name=' + Search.QUERY + ']').attr('data-a');
		if (action.toUpperCase() == Action.AUTOCOMPLETEABILITY.toUpperCase()) {
			addButton(item);
			return '';
		} else if (action.toUpperCase() == Action.AUTOCOMPLETENAME
				.toUpperCase()) {
			$('input[name=' + Search.QUERY + ']').val(item);
			$('form#search').submit();
			return item;
		}
	}
	;

	setAutocomplete(Search.QUERY, Action.AUTOCOMPLETEABILITY, $('form#search'),
			mainSearchUpdater);

});

function justFriendAndSubmit() {
	$('input[name=filter]').val('nofriend');
	$('form#search').submit();
}

function justNoFriendAndSubmit() {
	$('input[name=filter]').val('friend');
	$('form#search').submit();
}

function setAutocompleteAction(name, action) {

	var oldAction = $('input[name=' + name + ']').attr('data-a') + '';

	$('input[name=' + name + ']').attr('data-a', action.toUpperCase());
	if (action.toUpperCase() == Action.AUTOCOMPLETEABILITY.toUpperCase()) {
		$('input[name=' + name + ']').attr('placeholder',
				'Type one or a few abilities...');
		$('#chooseName').removeClass('disabled');
		$('#chooseAbility').addClass('disabled');
	} else if (action.toUpperCase() == Action.AUTOCOMPLETENAME.toUpperCase()) {
		$('input[name=' + name + ']').attr('placeholder',
				'Type name of a user...');
		$('#chooseName').addClass('disabled');
		$('#chooseAbility').removeClass('disabled');
	}

	if (oldAction.toUpperCase() != Action.AUTOCOMPLETEABILITY.toUpperCase()
			|| action.toUpperCase() != oldAction.toUpperCase()) {
		$('#results').html('');
	}
}

function setAutocomplete(name, action, jqueryForm, updater) {
	var self = $('input[name=' + name + ']');
	self.attr('data-a', action);
	$('input[name=' + name + ']')
			.typeahead(
					{
						source : function(query, typeahead) {

							var data = {
								query : self.val(),
								a : self.attr('data-a'), // action ->
							// a:[AUTOCOMPLETENAME
							// | AUTOCOMPLETE]
							};

							$
									.ajax({
										type : 'post',
										url : self.attr('data-url'),
										data : data,
										dataType : 'json',
										cache : false,
										success : function(data) {
											var arr = data;

											// console.log(data);

											// create json from fields form
											var form = objectifyForm(jqueryForm);
											self.data('active', true);

											var choosenValue = [];
											if (action.toUpperCase() == Action.AUTOCOMPLETEABILITY
													.toUpperCase()) {
												if (form
														.hasOwnProperty('abilities'))
													choosenValue = form.abilities;
											}

											var filteredArray = [];
											i = arr.length;
											console.log(form);
											var j = 0;
											while (i--) {
												if (arr[i] != choosenValue
														&& $.inArray(arr[i],
																choosenValue) == -1) {
													filteredArray[j] = arr[i];
													j++;
												}
											}

											arr = filteredArray;

											// self.data('typeahead').source =
											// arr;
											typeahead(arr);
										},
										error : function(jqXHR, textStatus,
												errorThrown) {
											console.log("Error: " + textStatus);
										}
									});
						},
						updater : function(item) {
							if (updater == null)
								return item;
							else
								return updater(item);

						}
					});
}

function addButton(result) {
	var newButton = $('<a class="btn btn-mini btn-remover" onclick="$(this).remove()"><input name="abilities" type="hidden" value="'
			+ result + '" >' + result + '</a>');
	$('#results').append(newButton);
}

function objectifyForm(form) {
	var fields = {};

	form.find(":input").each(function() {
		if (!fields.hasOwnProperty(this.name)) {
			fields[this.name] = $(this).val();
		} else {
			if ($.isArray(fields[this.name])) {
				fields[this.name].push($(this).val());
			} else {
				var oldValue = fields[this.name];
				fields[this.name] = [ oldValue, $(this).val() ];
			}
		}
	});

	return fields;

}